package com.nari.ncps.screen.service.impl.coal;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nari.ncps.screen.entity.coal.CoalProdoperSales;
import com.nari.ncps.screen.mapper.coal.CoalProdoperSalesMapper;
import com.nari.ncps.screen.service.coal.CoalProdoperSalesService;
import com.nari.ncps.screen.vo.coal.CoalSalesVO;
import com.nari.ncps.screen.vo.wholeproduct.AnnualActualSalesVO;
import com.nari.ncps.screen.vo.wholeproduct.AnnualSalesCompletionRateVO;
import com.nari.ncps.screen.vo.wholeproduct.AnnualSalesCompletionVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 生产经营煤炭销量表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class CoalProdoperSalesServiceImpl extends ServiceImpl<CoalProdoperSalesMapper, CoalProdoperSales> implements CoalProdoperSalesService {

    @Autowired
    private CoalProdoperSalesMapper coalProdoperSalesMapper;
    @Override
    public CoalSalesVO getCoalSales(Integer year) {
        // 如果year为null，使用当前年份
        int currentYear = year != null ? year : LocalDate.now().getYear();
        int currentMonth = LocalDate.now().getMonthValue();

        CoalSalesVO vo = new CoalSalesVO();
//        BigDecimal divisor = new BigDecimal("10000");  // 将吨转换为万吨

        // 查询年度数据（year_month_type = 0）
        LambdaQueryWrapper<CoalProdoperSales> yearQuery = new LambdaQueryWrapper<>();
        yearQuery.eq(CoalProdoperSales::getYear, currentYear);
//                .eq(CoalProdoperSales::getYearMonthType, false);  // false表示年度数据
        List<CoalProdoperSales> yearDataList = coalProdoperSalesMapper.selectList(yearQuery);


        // 汇总年度数据
        BigDecimal annualPlanTotal = BigDecimal.ZERO;
        BigDecimal annualActualTotal = BigDecimal.ZERO;

        BigDecimal annualHighHeat = BigDecimal.ZERO;  // coal_type = 0
        BigDecimal annualMidHeat = BigDecimal.ZERO;   // coal_type = 1
        BigDecimal annualLowHeat = BigDecimal.ZERO;   // coal_type = 2

        Optional<CoalProdoperSales> first = yearDataList.stream().filter(x -> x.getDateType() == 0).findFirst();
        if(first.isPresent()) {
            //annualLowHeat = first.get().getLowHeat();
           // annualMidHeat = first.get().getNormalHeat();
           // annualHighHeat = first.get().getGreatHeat();

            //少一个优热值 TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO
            //少一个优热值 TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO
            vo.setAnnualHighHeat(annualHighHeat);
           // vo.setAnnualMidHeat(annualMidHeat);
            vo.setAnnualLowHeat(annualLowHeat);

            vo.setAnnualPlan(first.get().getAnnualPlan());
            vo.setAnnualActual(first.get().getAnnualActual());
            vo.setAnnualCompletionRate(first.get().getAnnualCompletionRate());

        }

        // 写月份
        List<CoalProdoperSales> collect = yearDataList.stream().filter(x -> x.getDateType() == 1).toList();

        for(CoalProdoperSales coal : collect) {
          //  vo.setMonthlyHighHeat(coal.getGreatHeat());
         //   vo.setMonthlyMidHeat(coal.getNormalHeat());
          //  vo.setMonthlyLowHeat(coal.getLowHeat());

            vo.setMonthlyPlan(coal.getMonthlyPlan());
            vo.setMonthlyActual(coal.getMonthlyActual());
            vo.setMonthlyCompletionRate(coal.getMonthlyCompletionRate());
        }

        return vo;

//        for (CoalProdoperSales data : yearDataList) {
//            if (data.getAnnualPlan() != null) {
//                annualPlanTotal = annualPlanTotal.add(data.getAnnualPlan());
//            }
//            if (data.getAnnualActual() != null) {
//                annualActualTotal = annualActualTotal.add(data.getAnnualActual());
//
//                // 根据煤炭类型分类汇总：0：高热，1：中热，2：普热
//                if (data.getCoalType() != null) {
//                    if (data.getCoalType() == 0) {
//                        annualHighHeat = annualHighHeat.add(data.getAnnualActual());
//                    } else if (data.getCoalType() == 1) {
//                        annualMidHeat = annualMidHeat.add(data.getAnnualActual());
//                    } else if (data.getCoalType() == 2) {
//                        annualLowHeat = annualLowHeat.add(data.getAnnualActual());
//                    }
//                }
//            }
//        }
//
//        // 查询月度数据（year_month_type = 1, 当前月份）
//        LambdaQueryWrapper<CoalProdoperSales> monthQuery = new LambdaQueryWrapper<>();
//        monthQuery.eq(CoalProdoperSales::getYear, currentYear)
//                .eq(CoalProdoperSales::getMonth, currentMonth);
////                .eq(CoalProdoperSales::getYearMonthType, true);  // true表示月度数据
//        List<CoalProdoperSales> monthDataList = this.list(monthQuery);
//
//        // 汇总月度数据
//        BigDecimal monthlyPlanTotal = BigDecimal.ZERO;
//        BigDecimal monthlyActualTotal = BigDecimal.ZERO;
//        BigDecimal monthlyHighHeat = BigDecimal.ZERO;
//        BigDecimal monthlyMidHeat = BigDecimal.ZERO;
//        BigDecimal monthlyLowHeat = BigDecimal.ZERO;
//
//        for (CoalProdoperSales data : monthDataList) {
//            if (data.getMonthlyPlan() != null) {
//                monthlyPlanTotal = monthlyPlanTotal.add(data.getMonthlyPlan());
//            }
//            if (data.getMonthlyActual() != null) {
//                monthlyActualTotal = monthlyActualTotal.add(data.getMonthlyActual());
//
//                // 根据煤炭类型分类汇总：0：高热，1：中热，2：普热
//                if (data.getCoalType() != null) {
//                    if (data.getCoalType() == 0) {
//                        monthlyHighHeat = monthlyHighHeat.add(data.getMonthlyActual());
//                    } else if (data.getCoalType() == 1) {
//                        monthlyMidHeat = monthlyMidHeat.add(data.getMonthlyActual());
//                    } else if (data.getCoalType() == 2) {
//                        monthlyLowHeat = monthlyLowHeat.add(data.getMonthlyActual());
//                    }
//                }
//            }
//        }
//
//        // 设置年度数据（转换为万吨）
//        vo.setAnnualPlan(annualPlanTotal.divide(divisor, 2, RoundingMode.HALF_UP));
//        vo.setAnnualActual(annualActualTotal.divide(divisor, 2, RoundingMode.HALF_UP));
//        vo.setAnnualHighHeat(annualHighHeat.divide(divisor, 2, RoundingMode.HALF_UP));
//        vo.setAnnualMidHeat(annualMidHeat.divide(divisor, 2, RoundingMode.HALF_UP));
//        vo.setAnnualLowHeat(annualLowHeat.divide(divisor, 2, RoundingMode.HALF_UP));
//
//        // 计算年度完成率
//        if (annualPlanTotal.compareTo(BigDecimal.ZERO) > 0) {
//            BigDecimal annualRate = annualActualTotal
//                    .divide(annualPlanTotal, 4, RoundingMode.HALF_UP)
//                    .multiply(new BigDecimal("100"))
//                    .setScale(2, RoundingMode.HALF_UP);
//            vo.setAnnualCompletionRate(annualRate);
//        } else {
//            vo.setAnnualCompletionRate(BigDecimal.ZERO);
//        }
//
//        // 设置月度数据（转换为万吨）
//        vo.setMonthlyPlan(monthlyPlanTotal.divide(divisor, 2, RoundingMode.HALF_UP));
//        vo.setMonthlyActual(monthlyActualTotal.divide(divisor, 2, RoundingMode.HALF_UP));
//        vo.setMonthlyHighHeat(monthlyHighHeat.divide(divisor, 2, RoundingMode.HALF_UP));
//        vo.setMonthlyMidHeat(monthlyMidHeat.divide(divisor, 2, RoundingMode.HALF_UP));
//        vo.setMonthlyLowHeat(monthlyLowHeat.divide(divisor, 2, RoundingMode.HALF_UP));
//
//        // 计算月度完成率
//        if (monthlyPlanTotal.compareTo(BigDecimal.ZERO) > 0) {
//            BigDecimal monthlyRate = monthlyActualTotal
//                    .divide(monthlyPlanTotal, 4, RoundingMode.HALF_UP)
//                    .multiply(new BigDecimal("100"))
//                    .setScale(2, RoundingMode.HALF_UP);
//            vo.setMonthlyCompletionRate(monthlyRate);
//        } else {
//            vo.setMonthlyCompletionRate(BigDecimal.ZERO);
//        }
//
//        return vo;
    }

    @Override
    public AnnualSalesCompletionVO getAnnualSalesCompletion(Integer year) {
        // 如果year为null，使用当前年份
        int currentYear = year != null ? year : LocalDate.now().getYear();
        
        AnnualSalesCompletionVO vo = new AnnualSalesCompletionVO();
        BigDecimal divisor = new BigDecimal("10000");  // 将吨转换为万吨
        
        // 查询年度数据（year_month_type = 0, unit_code = 'TOTAL'）
        LambdaQueryWrapper<CoalProdoperSales> yearQuery = new LambdaQueryWrapper<>();
        yearQuery.eq(CoalProdoperSales::getYear, currentYear)
                .eq(CoalProdoperSales::getDateType, 0);
//                .eq(CoalProdoperSales::getYearMonthType, false)  // false表示年度数据
//                .eq(CoalProdoperSales::getOrgCode, "TOTAL");
        List<CoalProdoperSales> yearDataList = this.list(yearQuery);
        
        // 汇总所有煤炭类型的销量数据
        BigDecimal annualPlanTotal = BigDecimal.ZERO;
        BigDecimal annualActualTotal = BigDecimal.ZERO;
        
        for (CoalProdoperSales data : yearDataList) {
            if (data.getAnnualPlan() != null) {
                annualPlanTotal = annualPlanTotal.add(data.getAnnualPlan());
            }
            if (data.getAnnualActual() != null) {
                annualActualTotal = annualActualTotal.add(data.getAnnualActual());
            }
        }
        
        // 设置年度数据（转换为万吨）
        vo.setAnnualPlan(annualPlanTotal.divide(divisor, 2, RoundingMode.HALF_UP));
        vo.setAnnualActual(annualActualTotal.divide(divisor, 2, RoundingMode.HALF_UP));
        
        // 计算年度完成率
        if (annualPlanTotal.compareTo(BigDecimal.ZERO) > 0) {
            BigDecimal annualRate = annualActualTotal
                    .divide(annualPlanTotal, 4, RoundingMode.HALF_UP)
//                    .divide(annualPlanTotal, 4, RoundingMode.HALF_UP)

                    .multiply(new BigDecimal("100"))
                    .setScale(2, RoundingMode.HALF_UP);
            vo.setAnnualCompletionRate(annualRate);
        } else {
            vo.setAnnualCompletionRate(BigDecimal.ZERO);
        }
        
        return vo;
    }

    @Override
    public List<AnnualActualSalesVO> getAnnualActualSales(Integer year) {
        // 如果year为null，使用当前年份
        int currentYear = year != null ? year : LocalDate.now().getYear();
        
        // 计算最近5年的年份列表
        List<Integer> years = new ArrayList<>();
        for (int i = 4; i >= 0; i--) {
            years.add(currentYear - i);
        }
        
        List<AnnualActualSalesVO> resultList = new ArrayList<>();
        BigDecimal divisor = new BigDecimal("10000");  // 将吨转换为万吨
        
        // 查询最近5年的年度数据（year_month_type = 0, unit_code = 'TOTAL'）
        LambdaQueryWrapper<CoalProdoperSales> query = new LambdaQueryWrapper<>();
        query.in(CoalProdoperSales::getYear, years)
//             .eq(CoalProdoperSales::getYearMonthType, false)  // false表示年度数据
           //  .eq(CoalProdoperSales::getOrgCode, "100360")
             .orderByAsc(CoalProdoperSales::getYear);
        
        List<CoalProdoperSales> dataList = this.list(query);
        
        // 按年份汇总所有煤炭类型的实际销量
        for (Integer targetYear : years) {
            BigDecimal annualActualTotal = BigDecimal.ZERO;
            
            // 汇总该年份所有煤炭类型的实际销量
            for (CoalProdoperSales data : dataList) {
                if (data.getYear().equals(targetYear) && data.getAnnualActual() != null) {
                    annualActualTotal = annualActualTotal.add(data.getAnnualActual());
                }
            }
            
            // 创建VO并添加到结果列表
            AnnualActualSalesVO vo = new AnnualActualSalesVO();
            vo.setYear(targetYear);
            vo.setAnnualActual(annualActualTotal.divide(divisor, 2, RoundingMode.HALF_UP));
            resultList.add(vo);
        }
        
        return resultList;
    }

    @Override
    public List<AnnualSalesCompletionRateVO> getAnnualSalesCompletionRate(Integer year) {
        // 如果year为null，使用当前年份
        int currentYear = year != null ? year : LocalDate.now().getYear();
        
        // 计算最近5年的年份列表
        List<Integer> years = new ArrayList<>();
        for (int i = 3; i >= 0; i--) {
            years.add(currentYear - i);
        }
        
        List<AnnualSalesCompletionRateVO> resultList = new ArrayList<>();
        
        // 查询最近5年的年度数据（year_month_type = 0, unit_code = 'TOTAL'）
        LambdaQueryWrapper<CoalProdoperSales> query = new LambdaQueryWrapper<>();
        query.in(CoalProdoperSales::getYear, years)
//             .eq(CoalProdoperSales::getYearMonthType, false)  // false表示年度数据
             .eq(CoalProdoperSales::getOrgCode, "100360")
                .eq(CoalProdoperSales::getDelFlag, 0)
             .orderByDesc(CoalProdoperSales::getYear);
        
        List<CoalProdoperSales> dataList = this.list(query);
        
        // 按年份汇总所有煤炭类型的计划和实际销量，并计算完成率
        for (Integer targetYear : years) {
            BigDecimal annualPlanTotal = BigDecimal.ZERO;
            BigDecimal annualActualTotal = BigDecimal.ZERO;
            
            // 汇总该年份所有煤炭类型的计划和实际销量
            for (CoalProdoperSales data : dataList) {
                if (data.getYear().equals(targetYear)) {
                    if (data.getAnnualPlan() != null) {
                        annualPlanTotal = annualPlanTotal.add(data.getAnnualPlan());
                    }
                    if (data.getAnnualActual() != null) {
                        annualActualTotal = annualActualTotal.add(data.getAnnualActual());
                    }
                }
            }
            
            // 创建VO并计算完成率
            AnnualSalesCompletionRateVO vo = new AnnualSalesCompletionRateVO();
            vo.setYear(targetYear);
            
            // 计算完成率：实际销量 / 计划销量 * 100
            if (annualPlanTotal.compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal completionRate = annualActualTotal
                        .divide(annualPlanTotal, 4, RoundingMode.HALF_UP)
                        .multiply(new BigDecimal("100"))
                        .setScale(2, RoundingMode.HALF_UP);
                vo.setAnnualCompletionRate(completionRate);
            } else {
                vo.setAnnualCompletionRate(BigDecimal.ZERO);
            }
            
            resultList.add(vo);
        }
        
        return resultList;
    }

}
